//
// Created by sherlock on 2021/3/14.
//

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

#define CUSTOMER_NUM 10

sem_t sem;

void *get_server(void *thread_id) {
    int cusotmer_id = *((int *) thread_id);
    if (sem_wait(&sem) == 0) {
        printf("customer %d receive server ...\n", cusotmer_id);
        sem_post(&sem);
    }
}

int main() {
    sem_init(&sem, 0, 2);
    pthread_t customers[CUSTOMER_NUM];
    int customer_id[CUSTOMER_NUM];//用户id

    for (int index = 0; index < CUSTOMER_NUM; index++) {
        customer_id[index] = index;
        printf("customer %d arrived\n", customer_id[index]);
        int res = pthread_create(&customers[index], nullptr, get_server, &customer_id[index]);
        if (res) {
            printf("create thread error\n");
            return res;
        }
    }
    for (int index = 0; index < CUSTOMER_NUM; index++) {
        pthread_join(customers[index], nullptr);
    }
    sem_destroy(&sem);

    return 0;
}
